import pymysql,time

# 引入增删改查的数据库函数
from basic.mysql import *

# 定义一个全局变量保存当前登录用户的用户名，初始为空
login_name = ''

# 判断一个字符串能否被转换为一个有效的数字
def check_number(string):
    point = 0
    isvalid = True
    for c in string:
        code = ord(c)
        if (code < 48 and code != 46) or code > 57:
            isvalid = False
            break
        elif code == 46:
            point += 1
    if point > 1: isvalid = False
    return isvalid

# 注册
def reg():
    username = input("[注册]请输入用户名：")
    pwd = input("[注册]请输入密码：")
    phone = input("[注册]请输入手机号码：")
    result = query_one("select username from user_info where username = '%s'" %username)
    if result != None:
        print("用户名已存在")
    else:
        db_operation("insert into user_info values ('%s','%s','%s',0)" %(username,pwd,phone))
        print("注册成功")
        start_menu()

# 登录
def login():
    username = input("[登录]请输入用户名：")
    pwd = input("[登录]请输入密码：")
    result = query_one("select password from user_info where username = '%s'" %username)
    if result != None:
        if result[0] == pwd:
            print("登录成功")
            global login_name
            login_name = username
            main_menu()
        else:
            print("密码错误")
            start_menu()
    else:
        print("用户不存在")
        login()

# 查询
def query():
    result = query_one("select * from user_info where username = '%s'" %login_name)
    output = result[0] + "\n" + "手机号："+ result[2] + "\n" + "余额："+ str(result[3])
    print(output)
    main_menu()

#  账户金额的操作
def change_balance(username, money):
    balance = query_one("select balance from user_info where username = '%s'" %username)
    new_balance = balance[0] + float(money)
    db_operation("update user_info set balance = %f where username = '%s'" % (new_balance, username))
    if float(money) > 0:
        print("成功存款%f，剩余金额%f" % (money, new_balance))
    else:
        print("成功取款%f，剩余金额%f" % (money * -1, new_balance))

# 取款
def withdraw():
    money = input("请输入你的取款金额：")
    balance = query_one("select balance from user_info where username = '%s'" %login_name)
    if check_number(money) and float(money) <= balance[0] and float(money) % 100 == 0:
        change_balance(login_name,float(money) * -1)
        string = time.strftime('%Y-%m-%d %H:%M:%S')+" "+"取款"+money
        db_operation("insert into history1(username,content)values('%s','%s')" %(login_name,string))
        main_menu()
    else:
        print("取款金额有误")
        withdraw()

# 存款
def deposite():
    money = input("请输入你的存款金额：")
    if check_number(money) and float(money) % 100 == 0:
        change_balance(login_name, float(money))
        string = time.strftime('%Y-%m-%d %H:%M:%S') + " " + "存款" + money
        db_operation("insert into history1(username,content)values('%s','%s')" % (login_name, string))
        main_menu()
    else:
        print("存款金额有误")
        deposite()

# 转账
def transer():
    account = input("请输入你的转账账号：")
    account_search = query_one("select username from user_info where username = '%s'" %account)
    if account_search != None and account != login_name:
        money = input("请输入你的转账金额：")
        if check_number(money):
            money = float(money)
            balance1 = query_one("select balance from user_info where username = '%s'" %login_name)
            if money <= balance1[0]:
                new_balance1 = balance1[0] - float(money)
                db_operation("update user_info set balance = %f where username = '%s'" % (new_balance1, login_name))
                print("成功转账%f！当前余额为：%f" %(money,new_balance1))
                balance2 = query_one("select balance from user_info where username = '%s'" %account)
                new_balance2 = balance2[0] + float(money)
                db_operation("update user_info set balance = %f where username = '%s'" % (new_balance2, account))
                print("另一个账户余额为：%f" %new_balance2)  # 方便检查另一个账户是否有进账
                string1 = time.strftime('%Y-%m-%d %H:%M:%S') + " " + "转出" + str(money)
                db_operation("insert into history1(username,content)values('%s','%s')" % (login_name, string1))
                string2 = time.strftime('%Y-%m-%d %H:%M:%S') + " " + "转入" + str(money)
                db_operation("insert into history1(username,content)values('%s','%s')" % (account, string2))
            else:
                print("余额不足")
                transer()
        else:
            print("你输入的金额不符合规范")
            transer()
    elif account == login_name:
        print("你输入的账号为当前账号")
        transer()
    else:
        print("你输入的账号不存在")
        transer()
    main_menu()

# 流水
def history():
    result = query_all("select username,content from history1 where username = '%s'" %login_name)
    if result ==():
        print('当前用户流水信息为空')
    else:
        for h in result:
            print(h[0] + ' ' + h[1])
    main_menu()

# 修改密码
def update_pwd():
    while '1' == '1':
        new_pwd1 = input("请输入新密码：")
        new_pwd2 = input("请重复输入新密码：")
        if new_pwd1 == new_pwd2:
            break
    db_operation("update user_info set password = '%s' where username = '%s'" %(new_pwd1,login_name))
    print("修改密码成功")
    main_menu()


# 开始菜单
def start_menu():
    tip = '''
********************* 欢迎来到蜗牛ATM *********************
********************** 请选择以下操作 *********************
****************** 1.注册  2.登录  3.退卡 *****************         
    '''
    print(tip)
    option = int(input("请输入你的选择："))
    if option == 1:
        reg()
    elif option == 2:
        login()
    elif option == 3:
        exit("退卡成功")

# 主菜单
def main_menu():
    tip = '''
***************************** 进入蜗牛ATM主菜单 *****************************
****************************** 请选择以下操作 *******************************
******************* 1. 查询   2. 取款   3. 存款   4. 转账 *******************
****************** 5. 流水  6. 修改密码   7. 返回   8. 退卡 *****************     
        '''
    print(tip)
    option = int(input("请输入你的选择："))
    if option == 1:
        query()
    elif option == 2:
        withdraw()
    elif option == 3:
        deposite()
    elif option == 4:
        transer()
    elif option == 5:
        history()
    elif option == 6:
        update_pwd()
    elif option == 7:
        start_menu()
    elif option == 8:
        exit('谢谢，欢迎下次光临.')


if __name__ == '__main__':
    start_menu()